<template>
  <div class="ai-chat">
    <div class="chat-header">
      <h3>🤖 AI 分子问答</h3>
      <p>与AI助手讨论当前分子结构和相关科学问题</p>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" 
           :class="['message', message.role]">
        <div class="message-content">
          <div class="message-avatar">
            <span v-if="message.role === 'user'">👤</span>
            <span v-else>🤖</span>
          </div>
          <div class="message-text">
            <p v-if="message.role === 'assistant' && isStreaming && message === messages[messages.length - 1]">
              {{ currentAIResponse }}
              <span class="typing-cursor">|</span>
            </p>
            <p v-else>{{ message.content }}</p>
            <span class="message-time">{{ formatTime(message.timestamp) }}</span>
          </div>
        </div>
      </div>
      
      <div v-if="loading && !isStreaming" class="message assistant">
        <div class="message-content">
          <div class="message-avatar">🤖</div>
          <div class="message-text">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <div class="input-group">
        <input
          v-model="userInput"
          placeholder="输入您关于分子的问题..."
          @keyup.enter="sendMessage"
          :disabled="loading"
        />
        <button @click="sendMessage" :disabled="loading || !userInput.trim()">
          {{ loading ? '发送中...' : '发送' }}
        </button>
      </div>
      
      <div class="suggestions">
        <button
          v-for="(suggestion, index) in quickSuggestions"
          :key="index"
          @click="selectSuggestion(suggestion)"
          class="suggestion-btn"
          :disabled="loading"
        >
          {{ suggestion }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { apiService } from '../services/apiService.js'

const props = defineProps({
  materialData: {
    type: Object,
    default: null
  },
  structureData: {
    type: Object,
    default: null
  }
})

const messages = ref([])
const userInput = ref('')
const loading = ref(false)
const messagesContainer = ref(null)
const currentAIResponse = ref('')
const isStreaming = ref(false)

const quickSuggestions = [
  '这个分子的化学性质是什么？',
  '请解释这个分子的晶体结构',
  '这个材料有什么应用前景？',
  '合成这个分子的方法有哪些？'
]

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

const sendMessage = async () => {
  if (!userInput.value.trim() || loading.value) return

  const userMessage = {
    role: 'user',
    content: userInput.value.trim(),
    timestamp: new Date()
  }

  messages.value.push(userMessage)
  userInput.value = ''
  loading.value = true
  isStreaming.value = true
  currentAIResponse.value = ''
  scrollToBottom()

  try {
    // 获取AI设置
    let aiSettings = {
      temperature: 0.7,
      maxTokens: 7000
    }
    
    try {
      const savedSettings = localStorage.getItem('appSettings')
      if (savedSettings) {
        const settings = JSON.parse(savedSettings)
        aiSettings.temperature = settings.aiTemperature || aiSettings.temperature
        aiSettings.maxTokens = settings.aiMaxTokens || aiSettings.maxTokens
      }
    } catch (error) {
      console.error('加载AI设置失败:', error)
    }

    // 调用AI API流式响应
    const stream = await apiService.aiChatStream(
      userMessage.content,
      props.materialData,
      aiSettings.temperature,
      aiSettings.maxTokens
    )

    // 创建AI响应消息
    const aiMessage = {
      role: 'assistant',
      content: '',
      timestamp: new Date()
    }
    messages.value.push(aiMessage)

    // 处理流式响应
    for await (const chunk of stream) {
      if (chunk.content) {
        currentAIResponse.value += chunk.content
        aiMessage.content = currentAIResponse.value
        scrollToBottom()
      }
      
      if (chunk.is_final) {
        break
      }
    }

    // 完成响应
    isStreaming.value = false
    currentAIResponse.value = ''

  } catch (error) {
    console.error('AI聊天错误:', error)
    messages.value.push({
      role: 'assistant',
      content: '抱歉，我暂时无法回答这个问题。请稍后再试。',
      timestamp: new Date()
    })
    isStreaming.value = false
    currentAIResponse.value = ''
  } finally {
    loading.value = false
    scrollToBottom()
  }
}

const selectSuggestion = (suggestion) => {
  userInput.value = suggestion
  sendMessage()
}

// 初始化欢迎消息
onMounted(() => {
  if (props.materialData) {
    messages.value.push({
      role: 'assistant',
      content: `您好！我是分子AI助手。我可以帮您分析 ${props.materialData.formula_pretty} 材料的相关信息。请问您想了解什么？`,
      timestamp: new Date()
    })
  } else {
    messages.value.push({
      role: 'assistant',
      content: '您好！我是分子AI助手。请先选择一个材料，然后我可以为您提供详细的分析和解答。',
      timestamp: new Date()
    })
  }
})

// 当材料数据变化时更新欢迎消息
watch(() => props.materialData, (newMaterial) => {
  if (newMaterial) {
    messages.value = [{
      role: 'assistant',
      content: `您好！现在我们可以讨论 ${newMaterial.formula_pretty} 材料了。请问您想了解什么关于这个分子的信息？`,
      timestamp: new Date()
    }]
  }
}, { immediate: true })
</script>

<style scoped>
.ai-chat {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
}

.chat-header {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  text-align: center;
}

.chat-header h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
}

.chat-header p {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f8f9fa;
}

.message {
  margin-bottom: 20px;
}

.message-content {
  display: flex;
  gap: 12px;
  max-width: 80%;
}

.message.user .message-content {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e9ecef;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
}

.message.user .message-avatar {
  background: #007bff;
  color: white;
}

.message-text {
  background: white;
  padding: 12px 16px;
  border-radius: 18px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message.user .message-text {
  background: #007bff;
  color: white;
}

.message-text p {
  margin: 0 0 8px 0;
  line-height: 1.5;
  white-space: pre-wrap;
}

.message-time {
  font-size: 11px;
  opacity: 0.6;
  display: block;
  text-align: right;
}

.message.user .message-time {
  text-align: left;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 0;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #6c757d;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

.typing-cursor {
  animation: blink 1s infinite;
  color: #007bff;
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0;
  }
}

.chat-input {
  padding: 20px;
  background: white;
  border-top: 1px solid #e9ecef;
}

.input-group {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.input-group input {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid #e9ecef;
  border-radius: 25px;
  outline: none;
  font-size: 14px;
}

.input-group input:focus {
  border-color: #007bff;
}

.input-group button {
  padding: 12px 20px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
}

.input-group button:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.input-group button:hover:not(:disabled) {
  background: #0056b3;
}

.suggestions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.suggestion-btn {
  padding: 8px 16px;
  background: #e9ecef;
  border: 1px solid #dee2e6;
  border-radius: 20px;
  cursor: pointer;
  font-size: 12px;
  color: #495057;
  transition: all 0.2s;
}

.suggestion-btn:hover:not(:disabled) {
  background: #dee2e6;
  transform: translateY(-1px);
}

.suggestion-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>